﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;

namespace 初级算法.其他
{
    public class 汉明距离
    {      
        /// <summary>
        /// https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnyode/
        /// </summary>
        public class Solution
        {
            public int HammingDistance(int x, int y)
            {
                BitArray xbitArray = new BitArray(BitConverter.GetBytes(x));
                BitArray ybitArray = new BitArray(BitConverter.GetBytes(y));

               // xbitArray.Xor(ybitArray);

                int num = 0;
                for (var i = 0; i < xbitArray.Length; i++)
                {
                    if (xbitArray[i] != ybitArray[i]) num++;
                }
                return num;
            }
            /// <summary>
            /// 执行用时：48 ms, 在所有 C# 提交中击败了63.97%的用户
            /// 内存消耗：15.7 MB, 在所有 C# 提交中击败了7.62%的用户
            /// </summary>
            /// <param name="x"></param>
            /// <param name="y"></param>
            /// <returns></returns>
            public int HammingDistance2(int x, int y)
            {
                return Convert.ToString(x ^ y, 2).Count(c => c == '1');
            }
        }

        ITestOutputHelper output;

        public 汉明距离(ITestOutputHelper output)
        {
            this.output = output;
        }


        [Fact]
        public void Test1()
        {
            Solution solution = new Solution();
            output.WriteLine("" + solution.HammingDistance(1, 4));
            output.WriteLine("" + solution.HammingDistance(3, 1));
            output.WriteLine("" + solution.HammingDistance(3, int.MaxValue));
            output.WriteLine("");
            output.WriteLine("" + solution.HammingDistance2(1, 4));
            output.WriteLine("" + solution.HammingDistance2(3, 1));
            output.WriteLine("" + solution.HammingDistance2(3, int.MaxValue));
        }
    }
}
